package com.netwit.service.impl;

import com.netwit.common.service.CommonService;
import com.netwit.service.ExportSQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExportSQLImpl implements ExportSQL {
    private Logger logger = LoggerFactory.getLogger(ExportSQLImpl.class);

    @Autowired
    CommonService service;

    @Override
    public String exportPaper(String uuid) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("alias", "qbanks");
        map.put("tableName", "q_questionbank");
        return exportSql(map);
    }

    private String exportSql(Map<String, Object>map){
        List<Map<String, Object>> result = service.query(map);
        if (result.size() > 0) {
            String tpl = "REPLACE INTO {0}{1} VALUES {2};";

            String columns = columnsFromMap(result.get(0));
            String tbl = (String) map.get("tableName");
            String values = valuesFromList(result);

            MessageFormat mf = new MessageFormat(tpl);
            String sql = mf.format(new Object[]{tbl, columns, values});
            return sql;
        } else {
            return "";
        }
    }

    private String columnsFromMap(Map<String, Object> map) {
        String columns = "";
        for (Map.Entry<String, Object> en : map.entrySet()) {
            columns += (columns.length() > 0 ? "," : "") + en.getKey();
        }
        return StringUtils.isEmpty(columns) ? "" : "(" + columns + ")";
    }

    private String valuesFromList(List<Map<String, Object>> result) {
        if (result.size() > 0) {
            StringBuilder values = new StringBuilder();
            for (Map<String, Object> row : result) {
                values.append(values.length() > 0 ? "," : "").append("(");
                int i = 0;
                for (Map.Entry<String, Object> en : row.entrySet()) {
                    values.append(i != 0 ? ", " : "");
                    values.append(en.getValue() == null ? "NULL" : "'" + en.getValue() + "'");
                    i++;
                }
                values.append(")");
            }
            return values.toString();
        }
        return null;
    }
}
